package com.jhgsys.internal.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.jhgsys.internal.common.annotation.Limit;
import com.jhgsys.internal.common.authentication.ShiroHelper;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.properties.FebsProperties;
import com.jhgsys.internal.common.utils.CaptchaUtil;
import com.jhgsys.internal.common.utils.MD5Util;
import com.jhgsys.internal.monitor.entity.LoginLog;
import com.jhgsys.internal.monitor.service.ILoginLogService;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IUserService;
import com.wf.captcha.Captcha;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MrBird
 */
@Validated
@RestController
public class LoginController extends BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private ILoginLogService loginLogService;
    @Autowired
    private FebsProperties febsProperties;
    @Autowired
    ShiroHelper      shiroHelper;
    /**
     * 登录验证
     * 默认用户
     * sysadmin 1234qwer
     * admin 123456
     *
     * @param userName
     * @param password
     * @param verifyCode
     * @param rememberMe
     * @param request
     * @return
     * @throws FebsException
     */
    @PostMapping("login")
    @Limit(key = "login", period = 60, count = 500, name = "登录接口", prefix = "limit")
    public FebsResponse login(
            @NotBlank(message = "{required}") String userName,
            @NotBlank(message = "{required}") String password,
            @NotBlank(message = "{required}") String verifyCode,
            boolean rememberMe, HttpServletRequest request) throws FebsException {
        if (!CaptchaUtil.verify(verifyCode, request)) {
            throw new FebsException("验证码错误！");
        }
        password = MD5Util.encrypt(userName.toLowerCase(), password);
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password, rememberMe);
        try {
            super.login(token);
            // 保存登录日志
            LoginLog loginLog = new LoginLog();
            loginLog.setUserName(userName);
            loginLog.setSystemBrowserInfo();
            this.loginLogService.saveLoginLog(loginLog);

            return new FebsResponse().success();
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
            throw new FebsException(e.getMessage());
        } catch (AuthenticationException e) {
            throw new FebsException("认证失败！");
        }
    }

    @PostMapping("regist")
    public FebsResponse regist(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String password) throws FebsException {
        User user = userService.findByName(username);
        if (user != null) {
            throw new FebsException("该用户名已存在");
        }
        this.userService.regist(username, password);
        return new FebsResponse().success();
    }

    @GetMapping("index/{username}")
    public FebsResponse index(@NotBlank(message = "{required}") @PathVariable String username) {
        // 更新登录时间
        this.userService.updateLoginTime(username);
        Map<String, Object> data = new HashMap<>();
        // 获取系统访问记录
        Long totalVisitCount = this.loginLogService.findTotalVisitCount();
        data.put("totalVisitCount", totalVisitCount);
        Long todayVisitCount = this.loginLogService.findTodayVisitCount();
        data.put("todayVisitCount", todayVisitCount);
        Long todayIp = this.loginLogService.findTodayIp();
        data.put("todayIp", todayIp);
        // 获取近期系统访问记录
        List<Map<String, Object>> lastSevenVisitCount = this.loginLogService.findLastSevenDaysVisitCount(null);
        data.put("lastSevenVisitCount", lastSevenVisitCount);
        User param = new User();
        param.setUserName(username);
        List<Map<String, Object>> lastSevenUserVisitCount = this.loginLogService.findLastSevenDaysVisitCount(param);
        data.put("lastSevenUserVisitCount", lastSevenUserVisitCount);
        return new FebsResponse().success().data(data);
    }

    @GetMapping("images/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.outPng(110, 34, 4, Captcha.TYPE_ONLY_NUMBER, request, response);
    }


    @GetMapping("wechatLogin")
    @Limit(key = "login", period = 60, count = 500, name = "登录接口", prefix = "limit")
  @ResponseBody  public FebsResponse login(@NotBlank(message = "{required}") String code,HttpServletResponse response) throws FebsException {
        RestTemplate  restTemplate=new RestTemplate();
        String  coprid=febsProperties.getCoprid();
        String  corpsecret=febsProperties.getCorpsecret();
        String accessTokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+coprid
                +"&corpsecret="+corpsecret;
        JSONObject accessTokenJson = restTemplate.getForObject(accessTokenUrl, JSONObject.class);
        if(accessTokenJson==null || StringUtils.isEmpty(accessTokenJson.getString("access_token"))){
            throw new FebsException("获取accseeToken失败!");
        }
        String  access_token=accessTokenJson.getString("access_token");
        String getUser="https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?";
        getUser+="access_token="+access_token+"&code="+code;
        JSONObject usrResponse = restTemplate.getForObject(getUser, JSONObject.class);
        if(usrResponse==null||usrResponse.getString("user_ticket")==null){
            throw new FebsException("code过期!");
        }
        String user_ticket=usrResponse.getString("user_ticket");
        String  getMobileUrl="https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=" +access_token;
        String  param="{\"user_ticket\":\""+user_ticket+"\"}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(param, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(getMobileUrl,
                                                                           entity, String.class);
        String responseBody = responseEntity.getBody();
        System.out.println(responseBody);
        JSONObject jsonObject=JSONObject.parseObject(responseBody);
        String  mobile= jsonObject.getString("mobile");
        String source="wechat";
        String password = MD5Util.encrypt(source, source);
        UsernamePasswordToken token = new UsernamePasswordToken(mobile, password, true);
        try {
            super.login(token);
            // 保存登录日志
            LoginLog loginLog = new LoginLog();
            loginLog.setUserName(mobile);
            loginLog.setSystemBrowserInfo();
            this.loginLogService.saveLoginLog(loginLog);
            User user = super.getCurrentUser();
            System.out.println("user"+user.toString());
            AuthorizationInfo authorizationInfo = shiroHelper.getCurrentuserAuthorizationInfo();
            JSONObject  result=new JSONObject();
            result.put("user", userService.findByName(user.getUserName())); // 获取实时的用户信息
            result.put("permissions", authorizationInfo.getStringPermissions());
            result.put("roles",authorizationInfo.getRoles());
            return new FebsResponse().success().data(result);
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
            throw new FebsException(e.getMessage());
        } catch (AuthenticationException e) {
            throw new FebsException("认证失败！");
        }
    }





}
